package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 热点评论处理
     * @param apComment 评论信息
     */
    @Override
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点文章评论===》开始");
        //TODO 1. 按照文章id   flag=1(热点文章)   点赞降序
        Query query = Query.query(Criteria.where("articleId").is(apComment.getArticleId())
                .and("flag").is(1))
                .with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        //TODO 2. 如果 热评集合为空  或  数量小于5 直接将当前评论改为热评
        if (apCommentList==null||apCommentList.size()<5){
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);
            return;
        }
        //TODO 3. 获取热评集合中 最后点赞数量最少的热评
        ApComment lastApComment = apCommentList.get(apCommentList.size() - 1);
        if (apComment.getLikes()>lastApComment.getLikes()){
            //当前评论改为热点评论
            apComment.setFlag((short)1);
            mongoTemplate.save(apComment);

            //将最后的评论改为普通评论
            lastApComment.setFlag((short)0);
            mongoTemplate.save(apComment);
        }
        log.info("异步计算热点文章==================> 结束");
    }
}
